import numpy as np
from scipy import stats
from scipy.stats import pearsonr,f_oneway

#描述统计
def get_stats(values):
    """
    根据给定的数值列表计算统计数据。
    
    参数:
    values (list): 包含数值数据的列表。
    
    返回:
    字典,包含以下统计数据:
        mean: 平均值
        median: 中位数
        std_dev: 标准差
        variance: 方差
        min: 最小值
        max: 最大值
        range: 全距
        quartiles: 四分位数 (25%, 50%, 75%)
    """
    values = np.array(values)
    mean = np.mean(values)
    median = np.median(values)
    std_dev = np.std(values)
    variance = np.var(values)
    minimum = np.min(values)
    maximum = np.max(values)
    range_val = np.ptp(values)
    quartiles = np.percentile(values, [25, 50, 75])

    return {
        "mean": mean.item(),
        "median": median.item(),
        "std_dev": std_dev.item(),
        "variance": variance.item(),
        "min": minimum.item(),
        "max": maximum.item(),
        "range": range_val.item(),
        "quartiles": quartiles.tolist(),
    }

#相关
def calculate_correlation(origin_data, column1_name, column2_name):
    if column1_name not in origin_data.columns or column2_name not in origin_data.columns:
        raise ValueError("指定的列名在数据中不存在。")

    corr_coefficient, _ = pearsonr(origin_data[column1_name], origin_data[column2_name])
    return corr_coefficient


#t检验
def ttest(data1, data2, alpha=0.05):
    t_stat, p_val = stats.ttest_ind(data1, data2)

    result = {
        "t_statistic": t_stat,
        "p_value": p_val
    }

    if p_val < alpha:
        result["conclusion"] = "拒绝原假设"
    else:
        result["conclusion"] = "不能拒绝原假设"

    return result

#方差分析
def anova(data, factors, alpha=0.05):
    if len(factors) != 1:
        return {"error": "Only one factor is allowed for single-factor ANOVA"}

    factor_name = factors[0]
    groups = {}

    for item in data:
        factor_value = item.get(factor_name)
        if factor_value is not None:
            for key, value in item.items():
                if key != factor_name and isinstance(value, (int, float)):
                    groups.setdefault(factor_value, []).append(value)
                    break

    filtered_groups = {group_name: group for group_name, group in groups.items() if len(group) >= 2}

    if not filtered_groups:
        return {"error": "Not enough data to perform ANOVA"}

    group_data = list(filtered_groups.values())
    f_val, p_val = f_oneway(*group_data)

    result = {
        "f_statistic": f_val,
        "p_value": p_val
    }

    if p_val < alpha:
        result["conclusion"] = "拒绝原假设"
    else:
        result["conclusion"] = "不能拒绝原假设"

    return result

